<template>
	<div :key="route.fullPath">
		<topNavigation :linkMsg="linkMsg"></topNavigation>
		<div style="display: flex; justify-content: center; margin-top: 5vh">
			<div style="width: 90vw">
				<div v-if="dataState" style="position: relative">
					<el-row style="display: flex; align-items: flex-start">
						<el-col :span="5">
							<div
								style="
									display: flex;
									flex-direction: column;
									justify-content: center;
								"
							>
								<el-card
									shadow="hover"
									style="
										position: relative;
										display: flex;
										flex-direction: column;
										align-items: center;
									"
								>
									<div
										style="
											margin-top: 7vh;
											display: flex;
											justify-content: center;
											align-items: flex-start;
											width: 100%;
										"
									>
										<el-text :icon="User" type="primary">
											<el-icon>
												<User />
											</el-icon>
											{{ userData.nickname }}</el-text
										>
									</div>
									<div>
										<div v-if="userData.notes">
											<typeWriter
												:msg="userData.notes"
											></typeWriter>
										</div>
										<div v-else>
											<typeWriter
												:msg="'您尚未登录...'"
											></typeWriter>
										</div>
									</div>
									<div
										style="
											display: flex;
											justify-content: space-between;
											align-items: flex-start;
											width: 100%;
											margin-top: 3vh;
										"
									>
										<el-text
											type="success"
											style="
												text-wrap: nowrap;
												margin-right: 5vw;
											"
										>
											<el-icon>
												<Clock />
											</el-icon>
											站龄{{ days }}天</el-text
										>
										<el-text
											type="warning"
											style="text-wrap: nowrap"
										>
											<el-icon><Edit /></el-icon>
											发布了{{ blogLength }}篇博客
										</el-text>
									</div>
									<div
										style="
											display: flex;
											justify-content: center;
											margin-top: 5vh;
										"
									>
										<el-button
											:type="btnType"
											plain
											round
											:disabled="btnDisabled"
											size="large"
											@click="followUser"
											style="width: 200px"
											>{{ btnText }}</el-button
										>
									</div>
								</el-card>

								<el-image
									fit="fill"
									:src="userData.avatar"
									style="
										z-index: 9;
										width: 100px;
										height: 100px;
										position: absolute;
										border-radius: 50%;
										top: -5vh;
										left: 7vw;
									"
								></el-image>
								<el-card
									shadow="hover"
									style="margin-top: 3vh; padding-bottom: 0"
								>
									<template #header>
										<div
											style="
												width: 100%;
												display: flex;
												justify-content: center;
												align-items: center;
											"
										>
											<el-text type="danger" size="large"
												><el-icon><Star /></el-icon
												>最新发布</el-text
											>
										</div>
									</template>
									<div
										style="
											width: 100%;
											display: flex;
											flex-direction: column;
											align-items: flex-start;
											justify-content: center;
										"
										v-for="(item, index) in newBlog"
										:key="index"
									>
										<el-link
											type="primary"
											@click="
												pushBlog(item.id, item.uploader)
											"
											style="font-size: small"
											:underline="false"
											>{{ item.title }}</el-link
										>
										<el-divider
											v-if="newBlog.length - 1 !== index"
										>
										</el-divider>
									</div>
								</el-card>
							</div>
						</el-col>
						<el-col :span="19">
							<div>
								<el-card
									id="new-blog-card"
									shadow="hover"
									style="
										min-height: 34vh;
										width: 90%;
										margin-left: 10%;
									"
								>
									<template #header>
										<div style="height: 5vh">
											<el-text
												size="large"
												style="
													font-size: 4vh;
													font-weight: bold;
												"
												type="danger"
											>
												{{ blogData[0].title }}</el-text
											>
										</div>
									</template>
									<div>
										<div
											v-html="blogData[0].content"
											style="line-height: 30px"
										></div>
									</div>
								</el-card>
							</div>
						</el-col>
					</el-row>
					<!-- 评论区 -->
					<el-row v-if="myUserData !== null && userLoginState">
						<el-col :span="24" style="width: 100%; margin-top: 5vh">
							<div ref="commentShowTarget">
								<commentShow
									v-if="commentShowTargetIsVisible"
									class="slideRightReturn"
									:commentData="comment"
									:userData="myUserData"
									@POSTCOMMENTS="postCommentHandle"
								></commentShow>
							</div>
						</el-col>
					</el-row>
					<el-row v-else>
						<el-col
							:span="24"
							style="
								margin-top: 5vh;
								display: flex;
								justify-content: center;
							"
						>
							<el-skeleton :rows="5" animated />
						</el-col>
					</el-row>
				</div>
				<div v-else>
					<el-skeleton :rows="10" animated />
				</div>
			</div>
		</div>
		<pageFooter></pageFooter>
	</div>
</template>

<script setup>
import { onBeforeMount, toRefs, watch } from 'vue';
import topNavigation from '../components/topNavigation.vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';
import { date } from '../store/date.js';
import { User, Clock, Edit, Star } from '@element-plus/icons-vue';
import typeWriter from '../components/typeWriter.vue';
import getFile from '../utils/getAssetsFile.js';
import pageFooter from '../components/pageFooter.vue';

//异步组件引入
import { useIntersectionObserver } from '@vueuse/core';
const commentShow = defineAsyncComponent(() =>
	import('../components/commentShow.vue')
);
const commentShowTarget = ref(null);
const commentShowTargetIsVisible = ref(false);
const { stop } = useIntersectionObserver(
	commentShowTarget,
	([{ isIntersecting }]) => {
		if (isIntersecting) {
			commentShowTargetIsVisible.value = isIntersecting;
		}
	}
);

const dateStore = date();
const router = useRouter();
const route = useRoute();

const { blogId, uploader } = route.query;
const BlogId = ref(blogId);
const Uploader = ref(uploader);
const userData = ref({});
const blogLength = ref({});
const blogData = ref([]);
const days = ref(0);
const title = ref('');
const dataState = ref(false);
const newBlog = ref([]);
const btnType = ref('danger');
const btnDisabled = ref(false);
const btnText = ref('关注');
const comment = ref([]);
const myUserData = ref(null);
const userLoginState = ref(false);

const linkMsg = [
	{
		linkName: '文章',
		linkMethod: () => {
			return router.push('/article');
		},
	},
	{
		linkName: '发现',
		linkMethod: () => {
			return router.push('/discover');
		},
	},
	{
		linkName: '留言板',
		linkMethod: () => {
			return router.push('/board');
		},
	},
];

const pushBlog = (blogId, uploader) => {
	router.push({ path: '/blogPage', query: { blogId, uploader } });
};

const postCommentHandle = async (commentContent) => {
	if (commentContent) {
		if (!localStorage.getItem('username')) {
			return ElNotification({
				title: 'Warning',
				message: '您还没有登录哦！',
				type: 'warning',
			});
		}
		try {
			const res = await axios({
				baseURL: 'http://localhost:5000',
				url: '/addBlogComment',
				method: 'post',
				data: {
					content: commentContent,
					commentator: localStorage.getItem('username'),
					reviewee: uploader,
					blogId,
				},
			});
			if (res.data.state === 'error') {
				return ElNotification({
					title: 'Error',
					message: '服务器错误',
					type: 'error',
				});
			} else {
				ElNotification({
					title: 'Success',
					message: '评论成功',
					type: 'success',
				});
				location.reload();
				try {
					const res = await axios({
						baseURL: 'http://localhost:5000',
						url: '/getBlogComment',
						method: 'post',
						data: {
							blogId: BlogId.value,
						},
					});
					if (res.data.state === 'error') {
						ElNotification({
							title: 'Error',
							message: '服务器错误',
							type: 'error',
						});
					} else if (res.data.state === 'none') {
						comment.value.push({
							state: 'none',
						});
					} else {
						comment.value = res.data.data;
					}
				} catch (error) {
					console.log(error);
				}
			}
		} catch (error) {
			console.log(error);
			return ElNotification({
				title: 'error',
				message: '请检查本地网络',
				type: 'error',
			});
		}
	} else {
		return ElNotification({
			title: 'Warning',
			message: '请再写点吧',
			type: 'warning',
		});
	}
};

const followUser = async () => {
	if (!localStorage.getItem('username')) {
		return ElNotification({
			title: 'Warning',
			message: '您还没有登录哦',
			type: 'warning',
		});
	} else if (localStorage.username === uploader) {
		return ElNotification({
			title: 'Warning',
			message: '不能关注自己哦',
			type: 'warning',
		});
	}
	try {
		const res = await axios({
			baseURL: 'http://localhost:5000',
			url: '/addUserFollow',
			method: 'post',
			data: {
				myusername: localStorage.getItem('username'),
				username: uploader,
			},
		});
		if (res.data.state === 'error') {
			return ElNotification({
				title: 'Error',
				message: '服务器错误',
				type: 'error',
			});
		} else {
			btnType.value = 'info';
			btnDisabled.value = true;
			btnText.value = '已关注';
			return ElNotification({
				title: 'Success',
				message: '关注成功',
				type: 'success',
			});
		}
	} catch (error) {
		console.log(error);
		return ElNotification({
			title: 'Warning',
			message: '关注失败，请检查本地网络',
			type: 'warning',
		});
	}
};

watch(route, () => {
	router.go(0);
});

onBeforeMount(async () => {
	if (localStorage.getItem('username')) {
		userLoginState.value = true;
		try {
			const res = await axios({
				baseURL: 'http://localhost:5000',
				url: '/getUserMsg',
				method: 'post',
				data: {
					state: 'basedUsername',
					username: localStorage.getItem('username'),
				},
			});
			if (res.data.state === 'error') {
				ElNotification({
					title: 'Error',
					message: '服务器错误',
					type: 'error',
				});
			} else {
				myUserData.value = res.data.data;
			}
		} catch (error) {
			console.log(error);
			ElNotification({
				title: 'Warning',
				message: '请检查本地网络',
				type: 'warning',
			});
		}
	} else {
		userLoginState.value = false;
	}

	try {
		const res = await axios({
			baseURL: 'http://localhost:5000',
			url: '/getUserMsg',
			method: 'post',
			data: {
				state: 'basedUsername',
				username: Uploader.value,
			},
		});
		if (res.data.state === 'error') {
			ElNotification({
				title: 'Error',
				message: '服务器错误',
				type: 'error',
			});
		} else {
			userData.value = res.data.data;
		}
	} catch (error) {
		console.log(error);
		ElNotification({
			title: 'Error',
			message: '服务器错误',
			type: 'error',
		});
	}
	if (myUserData.value) {
		let registDate = new Date(JSON.parse(userData.value.registdate));
		days.value = dateStore.getDaysBetweenDates(new Date(), registDate);
		if (!myUserData.value.avatar) {
			myUserData.value.avatar = getFile.getAssetsFile(
				'img',
				'未登录头像.png'
			);
		}
		if (!userData.value.nickname) {
			userData.value.nickname = `新用户${userData.value.id}号`;
		}
		if (!userData.value.avatar) {
			userData.value.avatar = getFile.getAssetsFile(
				'img',
				'未登录头像.png'
			);
		}
		if (!userData.value.notes) {
			userData.value.notes = '这个人很懒...';
		}
	} else {
		userData.value.avatar = getFile.getAssetsFile('img', '未登录头像.png');
		userData.value.nickname = '未登录用户';
	}

	try {
		const res = await axios({
			baseURL: 'http://localhost:5000',
			url: '/getUserBlog',
			method: 'post',
			data: {
				uploader: Uploader.value,
			},
		});
		if (res.data.state === 'error') {
			ElNotification({
				title: 'Error',
				message: '服务器错误',
				type: 'error',
			});
		} else {
			blogLength.value = res.data.data.length;
		}
	} catch (error) {
		console.log(error);
		ElNotification({
			title: 'Error',
			message: '服务器错误',
			type: 'error',
		});
	}
	try {
		const res = await axios({
			baseURL: 'http://localhost:5000',
			url: '/getAppointBlog',
			method: 'post',
			data: {
				id: blogId,
			},
		});
		if (res.data.state === 'error') {
			ElNotification({
				title: 'Error',
				message: '服务器错误',
				type: 'error',
			});
		} else {
			blogData.value = res.data.data;
		}
	} catch (error) {
		console.log(error);
		ElNotification({
			title: 'Error',
			message: '服务器错误',
			type: 'error',
		});
	}
	try {
		const res = await axios({
			baseURL: 'http://localhost:5000',
			url: '/getUserPartBlog',
			method: 'post',
			data: {
				limit: 10,
			},
		});
		if (res.data.state === 'error') {
			ElNotification({
				title: 'Error',
				message: '服务器错误',
				type: 'error',
			});
		} else {
			newBlog.value = res.data.data;
		}
	} catch (error) {
		console.log(error);
		ElNotification({
			title: 'Error',
			message: '服务器错误',
			type: 'error',
		});
	}
	if (localStorage.getItem('username')) {
		try {
			const res = await axios({
				baseURL: 'http://localhost:5000',
				url: '/judgeFollowExist',
				method: 'post',
				data: {
					myusername: localStorage.getItem('username'),
					username: Uploader.value,
					userId: userData.value.id,
				},
			});
			if (res.data.state === 'exist') {
				btnType.value = 'info';
				btnDisabled.value = true;
				btnText.value = '已关注';
			}
		} catch (error) {
			console.log(error);
			ElNotification({
				title: 'Error',
				message: '服务器错误',
				type: 'error',
			});
		}
	} else {
		btnType.value = 'info';
		btnDisabled.value = false;
		btnText.value = '尚未登录';
	}

	try {
		const res = await axios({
			baseURL: 'http://localhost:5000',
			url: '/getBlogComment',
			method: 'post',
			data: {
				blogId: BlogId.value,
			},
		});
		if (res.data.state === 'error') {
			ElNotification({
				title: 'Error',
				message: '服务器错误',
				type: 'error',
			});
		} else if (res.data.state === 'none') {
			comment.value.push({
				state: 'none',
			});
		} else {
			comment.value = res.data.data;
		}
	} catch (error) {
		console.log(error);
	}

	dataState.value = true;
});
</script>

<style scoped>
.slideRightReturn {
	animation-duration: 1s;
}
</style>
